package com.lujianfei.androidthread.threadsActivity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.lujianfei.androidthread.R;

public class AsyncTaskActivity extends AppCompatActivity {

    final static String TAG = "AsyncTaskActivity==";
    TextView txt_info;
    MyAsynTask myAsynTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task);
        txt_info = findViewById(R.id.txt_info);
        myAsynTask = new MyAsynTask();
        myAsynTask.execute("finish tips");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != myAsynTask) {
            myAsynTask.cancel(true);
        }
    }

    class MyAsynTask extends AsyncTask<String,String,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // UI 线程, 执行顺序:开始
            txt_info.setText("loading...");
            Log.d(TAG,"onPreExecute thread:" + Thread.currentThread().getName());
        }

        @Override
        protected String doInBackground(String... strings) {
            // 子线程, 执行顺序:2
            Log.d(TAG,"doInBackground thread:" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return strings[0];
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            // UI 线程, 执行顺序:结束
            Log.d(TAG,"onPostExecute thread:" + Thread.currentThread().getName());
            txt_info.setText(s);
        }
    }
}
